package com.atguigu.zk.monitorupdown;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务消费者
 */
public class ServiceConsumer {
    private String connectString = "lc01:2181,lc02:2181,lc03:2181";
    private int sessionTimeOut = 2000;
    private ZooKeeper zooKeeper = null;

    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {
        ServiceConsumer serviceConsumer = new ServiceConsumer();
        // 1 获取zk连接
        serviceConsumer.connect();
        // 2 监听/server下的每个子节点的变化
        serviceConsumer.watch();
        // 3 执行服务的业务逻辑
        serviceConsumer.business();

    }

    private void watch() throws KeeperException, InterruptedException {
        List<String> servers = new ArrayList<>();

        List<String> children = zooKeeper.getChildren("/servers", true);
        for (String child : children) {
            // 获取各个servers下子节点对应的value
            byte[] data = zooKeeper.getData("/servers/" + child, false, null); // 这一步就没必要监听
            servers.add(new String(data));
        }
        System.out.println("获取到存活的服务器信息：" + servers);
    }

    private void business() throws InterruptedException {
        // 延时阻塞，保持线程不会终结
        Thread.sleep(Long.MAX_VALUE);
    }

    private void connect() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 时刻监控着服务器信息的变化
                try {
                    System.out.println("---------触发监听器开始----------");
                    watch();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("---------触发监听器结束----------");
                }
            }
        });
    }
}
